package com.cqrt.aop;

import cn.hutool.core.collection.CollUtil;
import com.cqrt.constant.RTErrorCodeEnum;
import com.hustcad.plm.pdm.core.handle.exception.ErrorCodeEnum;
import com.hustcad.plm.pdm.core.handle.exception.SystemErrorCodeEnum;
import com.hustcad.plm.rpm.model.dto.plan.TyppmBaselinePlanCreateDTO;
import com.hustcad.plm.rpm.model.entity.plan.TyppmBaselinePlan;
import com.hustcad.plm.rpm.model.entity.plan.TyppmBaselinePlanActivity;
import com.hustcad.plm.rpm.service.plan.TyppmBaselinePlanActivityService;
import com.hustcad.plm.rpm.service.plan.TyppmBaselinePlanService;
import com.ty.basic.constant.TableTypeConstrant;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Aspect
@Component
@Slf4j
public class ProjectBaseLineAop {
    @Resource
    private TyppmBaselinePlanService baselinePlanActivityService;

    /**
     * 删除基线时候，判断基线是否是 初始计划
     * @param joinPoint
     */
//    @Before("execution(* com.hustcad.plm.rpm.service.plan.TyppmBaselinePlanService.deleteBaseLinePlanByOid(..))")
    public void beforeDeleteBaseLine(JoinPoint joinPoint) {
        String oid = (String) joinPoint.getArgs()[0];
        TyppmBaselinePlan baselinePlan = baselinePlanActivityService.selectOneByOID(oid);
        if(!Objects.isNull(baselinePlan)){
            String name = baselinePlan.getBaselineName();
            if("初始计划".equals( name)){
                throw RTErrorCodeEnum.PROJECT_PARAMETER_NOT_EXIST.message("基线初始计划不允许被删除");
            }
        }
    }

    /**
     * 新增基线名称判重
     * @param joinPoint
     */
//    @Before("execution(* com.hustcad.plm.rpm.service.plan.TyppmBaselinePlanService.createPlanBaseline(..))")
    public void beforeCreateBaseLine(JoinPoint joinPoint) {
        TyppmBaselinePlanCreateDTO dto = (TyppmBaselinePlanCreateDTO) joinPoint.getArgs()[0];
        List<TyppmBaselinePlan> baselinePlans = baselinePlanActivityService.queryBaselinePlanPageByParent(dto.getPlanOid(), TableTypeConstrant.TY_PROJECT_TYPE, 1, 999).getList();
        if(CollUtil.isNotEmpty(baselinePlans)){
            Optional<TyppmBaselinePlan> first = baselinePlans.stream().filter(
                    item -> "name".equals(item.getBaselineName())).findFirst();
            if(first.isPresent()){
                throw RTErrorCodeEnum.PROJECT_PARAMETER_NOT_EXIST.message("名称为:" + dto.getBaselineName() + "的基线已存在,不允许新增");
            }
        }
    }
}
